
<template>
  <div class="container dark-theme">
    <!-- 头部导航栏 -->
    <div class="header">
      <div class="back-button" @click="goBack">
        <i class="el-icon-arrow-left"></i> 返回
      </div>
      <div class="title">活动详情</div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <el-spinner></el-spinner>
      <span>加载中...</span>
    </div>

    <!-- 错误提示 -->
    <div v-else-if="error" class="error">
      <p>{{ error }}</p>
      <el-button type="primary" @click="fetchActivityDetail">重试</el-button>
    </div>

    <!-- 主要内容区域 -->
    <div v-else class="main-content">
      <div class="activity-info">
        <div class="activity-image">
          <img :src="activity.images || defaultImage" :alt="activity.title">
        </div>
        <div class="activity-details">
          <h2>{{ activity.title || '未知活动' }}</h2>
          <h3>{{ activity.subTitle || '暂无副标题' }}</h3>
          <div class="store-info">
            <i class="el-icon-shop"></i>
            <span>{{ activity.organizerName || '未知组织者' }}</span>
          </div>
          <div class="store-info">
            <i class="el-icon-message"></i>
            <span>{{ activity.organizerContact || '暂无联系方式' }}</span>
          </div>
          <div class="tags">
            <span v-if="activity.currentPrice < activity.originalPrice" class="tag special">特价</span>
            <span v-if="isNewActivity(activity.createTime)" class="tag new">新活动</span>
            <span v-if="activity.status === 1" class="tag hot">热门</span>
          </div>
          <!-- 活动日期选择 -->
          <div class="date-selector">
            <label>选择活动日期：</label>
            <el-date-picker
              v-model="selectedDate"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
              @change="handleDateChange"
            ></el-date-picker>
          </div>
          <!-- 时间段选择 -->
          <div v-if="availableTimeSlots.length > 0" class="time-slot-selector">
            <label>选择活动时间段：</label>
            <el-select
              v-model="selectedTimeSlot"
              placeholder="请选择时间段"
              @change="handleTimeSlotChange"
            >
              <el-option
                v-for="slot in availableTimeSlots"
                :key="slot.id"
                :label="`${formatTime(slot.activityStartTime)} 至 ${formatTime(slot.activityEndTime)}`"
                :value="slot.id"
                :disabled="slot.stock <= 0 || !isWithinRegistrationPeriodForSlot(slot)"
              ></el-option>
            </el-select>
          </div>
          <!-- 活动时间显示 -->
          <div v-if="selectedDateInfo" class="activity-time">
            <p>活动时间：{{ formatTime(selectedDateInfo.activityStartTime) }} 至 {{ formatTime(selectedDateInfo.activityEndTime) }}</p>
            <p>可报名时间：{{ formatTime(selectedDateInfo.startTime) }} 至 {{ formatTime(selectedDateInfo.endTime) }}</p>
            <p :class="{ 'out-of-registration': !isWithinRegistrationPeriod }">当前状态：{{ isWithinRegistrationPeriod ? '在报名时间内' : '不在报名时间内' }}</p>
          </div>
<!--          <div v-else-if="selectedDate" class="activity-time error">-->
<!--            <p>所选日期无有效活动时间或库存</p>-->
<!--          </div>-->
        </div>
      </div>

      <!-- 活动描述 -->
      <div class="description-section">
        <h3>活动描述</h3>
        <p>{{ activity.description || '暂无描述' }}</p>
      </div>

      <!-- 购买按钮 -->
      <div class="purchase-actions">
        <el-button
          type="danger"
          @click="buyNow"
          :disabled="activity.status !== 1 || !selectedDate || !selectedTimeSlot || !isWithinRegistrationPeriod"
        >
          立即报名
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import dayjs from 'dayjs';

export default {
  name: 'ActivityDetail',
  data() {
    return {
      activity: null,
      defaultImage: 'https://via.placeholder.com/150',
      imageBaseUrl: 'http://localhost:8089',
      loading: false,
      error: null,
      selectedDate: null,
      selectedTimeSlot: null, // 存储所选时间段的 id
      selectedDateInfo: null, // 存储所选时间段的详细信息
      availableTimeSlots: [], // 存储所选日期的可用时间段
      user: null
    };
  },
  computed: {
    pickerOptions() {
      return {
        disabledDate: (date) => this.isDisabledDate(date),
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const today = dayjs().toDate();
              picker.$emit('pick', today);
            }
          },
          {
            text: '明天',
            onClick(picker) {
              const tomorrow = dayjs().add(1, 'day').toDate();
              picker.$emit('pick', tomorrow);
            }
          },
          {
            text: '后天',
            onClick(picker) {
              const afterTomorrow = dayjs().add(2, 'day').toDate();
              picker.$emit('pick', afterTomorrow);
            }
          }
        ]
      };
    },
    totalStock() {
      return this.activity.checkinDates.reduce((sum, item) => sum + (item.stock || 0), 0);
    },
    isWithinRegistrationPeriod() {
      if (!this.selectedDateInfo) return false;
      const now = dayjs();
      const startTime = dayjs(this.selectedDateInfo.startTime);
      const endTime = dayjs(this.selectedDateInfo.endTime);
      return now.isAfter(startTime) && now.isBefore(endTime);
    }
  },
  created() {
    this.fetchActivityDetail();
  },
  methods: {
    async fetchActivityDetail() {
      this.loading = true;
      this.error = null;
      try {
        const activityId = this.$route.params.id;
        if (!activityId) {
          throw new Error('活动ID缺失，请检查路由');
        }

        // 获取活动详情
        const activityResponse = await axios.get(`/commodity/activity/activity/${activityId}`, {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        if (!activityResponse.data.success) {
          throw new Error(activityResponse.data.errorMsg || '获取活动详情失败');
        }
        const activityData = Array.isArray(activityResponse.data.data)
          ? activityResponse.data.data[0]
          : activityResponse.data.data;
        if (!activityData) {
          throw new Error('活动数据为空');
        }

        // 获取组织者信息
        let organizerName = '未知组织者';
        let organizerContact = '暂无联系方式';
        try {
          const organizerResponse = await axios.get(`/commodity/organizer/${activityData.organizerId}`, {
            headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
          });
          if (organizerResponse.data.success && organizerResponse.data.data) {
            organizerName = organizerResponse.data.data.name || `组织者${activityData.organizerId}`;
            organizerContact = organizerResponse.data.data.contact || '暂无联系方式';
          }
        } catch (organizerError) {
          console.error('获取组织者信息失败:', organizerError);
        }

        // 获取活动时间和库存
        const timeResponse = await axios.get(`/commodity/activity/activityInfo/${activityId}`, {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        if (!timeResponse.data.success) {
          throw new Error(timeResponse.data.errorMsg || '获取活动时间段信息失败');
        }
        const timeData = Array.isArray(timeResponse.data.data)
          ? timeResponse.data.data
          : [timeResponse.data.data];

        // 存储 checkinDates，包含完整信息
        const checkinDates = timeData.map(item => ({
          id: item.id,
          activityStartTime: item.activityStartTime,
          activityEndTime: item.activityEndTime,
          startTime: item.startTime,
          endTime: item.endTime,
          stock: item.stock || 0,
          checkinDate: dayjs(item.activityStartTime).format('YYYY-MM-DD')
        }));

        this.activity = {
          ...activityData,
          organizerName,
          organizerContact,
          checkinDates
        };
      } catch (error) {
        this.error = error.message || '网络错误，请稍后重试';
      } finally {
        this.loading = false;
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    isNewActivity(createTime) {
      if (!createTime) return false;
      const createDate = new Date(createTime);
      const now = new Date();
      const diffDays = (now - createDate) / (1000 * 60 * 60 * 24);
      return diffDays <= 7;
    },
    isDisabledDate(date) {
      const formattedDate = dayjs(date).format('YYYY-MM-DD');
      const now = dayjs().startOf('day');
      const validSlots = this.activity.checkinDates.filter(d =>
        d.checkinDate === formattedDate &&
        d.stock > 0 &&
        dayjs().isAfter(dayjs(d.startTime)) &&
        dayjs().isBefore(dayjs(d.endTime))
      );
      return !validSlots.length || dayjs(formattedDate).isBefore(now);
    },
    isWithinRegistrationPeriodForSlot(slot) {
      const now = dayjs();
      const startTime = dayjs(slot.startTime);
      const endTime = dayjs(slot.endTime);
      return now.isAfter(startTime) && now.isBefore(endTime);
    },
    handleDateChange(date) {
      this.selectedTimeSlot = null;
      this.selectedDateInfo = null;
      this.availableTimeSlots = [];
      if (!date) {
        this.$message.warning('请选择有效的活动日期');
        this.selectedDate = null;
        return;
      }
      const formattedDate = dayjs(date).format('YYYY-MM-DD');
      const timeSlots = this.activity.checkinDates.filter(d =>
        d.checkinDate === formattedDate &&
        d.stock > 0
      );
      if (!timeSlots.length) {
        this.$message.warning('所选日期无有效活动时间或库存');
        this.selectedDate = null;
        return;
      }
      this.availableTimeSlots = timeSlots;
      if (timeSlots.length === 1) {
        this.selectedTimeSlot = timeSlots[0].id;
        this.handleTimeSlotChange(timeSlots[0].id);
      } else {
        this.$message.success(`已选择活动日期：${formattedDate}，请选择时间段`);
      }
    },
    handleTimeSlotChange(timeSlotId) {
      const slot = this.availableTimeSlots.find(s => s.id === timeSlotId);
      if (!slot || slot.stock <= 0) {
        this.$message.warning('所选时间段不可用或无库存');
        this.selectedTimeSlot = null;
        this.selectedDateInfo = null;
        return;
      }
      this.selectedDateInfo = slot;
      this.$message.success(
        `已选择时间段：${this.formatTime(slot.activityStartTime)} 至 ${this.formatTime(slot.activityEndTime)}`
      );
    },
    formatTime(time) {
      if (!time) return '未知';
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
    },
    async buyNow() {
      try {
        if (this.activity.status !== 1) {
          this.$message.warning('活动已下架，无法报名');
          return;
        }
        if (!this.selectedDate || !this.selectedTimeSlot || !this.selectedDateInfo) {
          this.$message.warning('请选择有效的活动日期和时间段');
          return;
        }
        if (!this.isWithinRegistrationPeriod) {
          this.$message.warning('当前不在活动报名时间内，无法报名');
          return;
        }

        const { data: userData } = await axios.get('/users/user/basic', {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        if (!userData.success || !userData.data) {
          this.$message.error('获取用户信息失败：无有效数据');
          return;
        }
        this.user = userData.data;

        const userId = this.user.id;
        const activityId = this.$route.params.id;
        const start = this.selectedDateInfo.activityStartTime; // 使用 activityStartTime

        if (!activityId) {
          this.$message.error('活动ID无效');
          return;
        }

        const { data } = await axios.post(
          `/commodity/activity-order/activityInfo/${activityId}?userId=${userId}&activityStartTime=${start}`,
          {},
          { headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } }
        );

        if (data.success) {
          this.$message.success(`报名成功，订单ID：${data.data}`);
          await this.fetchActivityDetail();
          this.selectedDate = null;
          this.selectedTimeSlot = null;
          this.selectedDateInfo = null;
          this.availableTimeSlots = [];
        } else {
          this.$message.error(data.errorMsg || '报名失败');
        }
      } catch (error) {
        this.$message.error('请求失败：' + (error.response?.data?.errorMsg || error.message));
      }
    }
  }
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: radial-gradient(ellipse at center, #001e3c 0%, #000 100%);
  color: #fff;
  font-family: 'Microsoft YaHei', sans-serif;
}

.header {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #002d52;
}

.back-button {
  cursor: pointer;
  color: #999;
  font-size: 16px;
}

.back-button:hover {
  color: #4fc3f7;
}

.title {
  margin-left: 20px;
  font-size: 20px;
  font-weight: bold;
}

.main-content {
  padding: 20px;
}

.activity-info {
  background: rgba(0, 45, 82, 0.8);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.activity-image {
  width: 100%;
  max-width: 400px;
  height: 300px;
}

.activity-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.activity-details {
  flex: 1;
}

.activity-details h2 {
  margin: 0 0 10px 0;
  color: #fff;
}

.activity-details h3 {
  margin: 0 0 10px 0;
  color: #e0e0e0;
  font-size: 18px;
}

.price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.original-price {
  color: #b0bec5;
  font-size: 16px;
  text-decoration: line-through;
  margin-left: 10px;
}

.store-info {
  color: #b0bec5;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.store-info i {
  margin-right: 5px;
}

.tags {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.tag.special {
  background: #f56c6c;
  color: #fff;
}

.tag.new {
  background: #67c23a;
  color: #fff;
}

.tag.hot {
  background: #e6a23c;
  color: #fff;
}

.date-selector,
.time-slot-selector {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.date-selector label,
.time-slot-selector label {
  color: #e0e0e0;
  font-size: 16px;
}

.activity-time {
  margin-bottom: 20px;
  color: #e0e0e0;
}

.activity-time p {
  margin: 5px 0;
}

.activity-time.error {
  color: #f56c6c;
}

.activity-time .out-of-registration {
  color: #f56c6c;
}

.description-section {
  background: rgba(0, 45, 82, 0.8);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.description-section h3 {
  margin: 0 0 10px 0;
  color: #fff;
}

.description-section p {
  color: #e0e0e0;
  line-height: 1.6;
  margin: 0;
}

.purchase-actions {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.el-button {
  padding: 12px 30px;
}

.el-button--danger {
  background: #f56c6c;
  border: 1px solid #f56c6c;
  color: #fff;
}

.el-button--danger:hover:not(:disabled) {
  background: #f78989;
  border-color: #f78989;
}

.el-button:disabled {
  background: #909399;
  border-color: #909399;
  color: #fff;
  cursor: not-allowed;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  color: #4fc3f7;
}

.error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  color: #f56c6c;
}

.error p {
  margin-bottom: 20px;
}
</style>
